package com.thejupitech;

import java.io.IOException;
import java.io.StringReader;
import java.net.URLEncoder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlBookParser {
	
	//Receive xml data of books 
	public static String getBooksXml(String keyword, String strUrl) {
		String strXml = null;
		keyword = URLEncoder.encode(keyword);
		keyword = keyword.replace("+", "%20");
		String url = strUrl.replace("keyword", keyword);		
		
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			strXml = EntityUtils.toString(httpEntity);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return strXml;
	}
	
	
	public static Document getXmlFromString(String strXml) {
		Document doc = null;		
		
		try {
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			
			InputSource is  = new InputSource();
			is.setCharacterStream(new StringReader(strXml));
			doc = db.parse(is);
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			
		return doc;
	}
	
	public static String getElementValue(Node element) {
		Node child;
		
		if(element != null) {
			if(element.hasChildNodes()) {
				for(child = element.getFirstChild(); child != null; child = child.getNextSibling()) {
					if(child.getNodeType() == Node.TEXT_NODE) {
						return child.getNodeValue();
					} 
				}
			}
		}
		return "";
	}
	
	public static String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return XmlBookParser.getElementValue(n.item(0));
	}
}
